/*
 * @Author: gitee_com_zb
 * @Date: 2024-12-12 17:07:16
 * @LastEditors: gitee_com_zb
 * @LastEditTime: 2024-12-12 17:07:29
 * @FilePath: /algorithm/每日一题12.删除链表的倒数第n个结点(medium).cpp
 * @Description: 题目链接 https://leetcode.cn/problems/remove-nth-node-from-end-of-list
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // 添加一个虚拟头结点,防止特殊情况要删除的就一个头结点
        // 思路: 快慢指针，快指针先走n步，然后同时走，快指针到尾，慢指针此时在倒数第n-1个位置
        ListNode *dummy = new ListNode(0, head);
        ListNode *fast = dummy, *slow = dummy;
        for(int i = 0; i < n + 1; i++) fast = fast->next;
        while(fast) {
            slow = slow->next;
            fast = fast->next;
        }
        ListNode *tmp = slow->next;
        slow->next = slow->next->next;
        delete tmp;
        return dummy->next;
    }
};